package com.leonardo.persistenceme.model.persistancehandlers;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.leonardo.beanme.OptionList;
import com.leonardo.beanme.model.ComboBox;
import com.leonardo.beanme.model.RadioBox;

public abstract class OptionListPersistenceHandler extends PersistenceHandler {

	public void persist(Object obj, DataOutputStream stream) throws IOException {
		if(obj == null) {
			stream.writeInt(-1);
			return;
		}
		OptionList combo = (OptionList) obj;
		stream.writeInt(combo.getSelectedIndex());
		String[] options = combo.getOptions();
		stream.writeInt(options.length);
		for(int i = 0; i < options.length; i++)
			stream.writeUTF(options[i]);
	}

	public Object recover(DataInputStream stream) throws IOException {
		int index = stream.readInt();
		if(index < 0)
			return null;
		int nOptions = stream.readInt();
		String[] options = new String[nOptions];
		for(int i = 0; i < nOptions; i++)
			options[i] = stream.readUTF(); 
		OptionList specific = getSpecific(options);
		specific.select(index);
		return specific;
	}
	
	protected abstract OptionList getSpecific(String[] options);
	
	public static class RadioBoxPersistenceHandler extends OptionListPersistenceHandler {

		protected OptionList getSpecific(String[] options) {
			return new RadioBox(options);
		}

	}
	
	public static class ComboBoxPersistenceHandler extends OptionListPersistenceHandler {

		protected OptionList getSpecific(String[] options) {
			return new ComboBox(options);
		}

	}



}
